package com.gyh.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gyh.entity.Course;
import com.gyh.entity.Member;
import com.gyh.entity.Reserve;
import com.gyh.mapper.CourseMapper;
import com.gyh.mapper.MemberMapper;
import com.gyh.mapper.ReserveMapper;
import com.gyh.service.ReserveService;
import com.gyh.vo.ReserveVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class ReserveServiceImpl extends ServiceImpl<ReserveMapper, Reserve> implements ReserveService {
    @Resource
    private ReserveMapper reserveMapper;
    @Resource
    private MemberMapper memberMapper;
    @Resource
    private CourseMapper courseMapper;
    @Override
    public int add(Reserve reserve) {
        /*1.判断会员是否已经预约该课程*/
        QueryWrapper<Reserve> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id",reserve.getCourseId())
                        .eq("member_id",reserve.getMemberId());
        Reserve dbReserve = reserveMapper.selectOne(queryWrapper);
        if (ObjectUtil.isNotEmpty(dbReserve)) {
            throw new RuntimeException("会员已经预约该课程");
        }
        /*2.判读会员是否存在*/
        Member member = memberMapper.selectById(reserve.getMemberId());
        if (ObjectUtil.isEmpty(member)) {
            throw new RuntimeException("会员不存在");
        }
        /*3.判读课程是否存在*/
        Course course = courseMapper.selectById(reserve.getCourseId());
        if (ObjectUtil.isEmpty(course)) {
            throw new RuntimeException("课程不存在");
        }
        /*4.上课后不能预约*/
        Date now = new Date();
        Date courseTime = course.getTime();
        Date endTime = new Date(courseTime.getTime() + course.getLength());
        if (now.after(courseTime)&&now.before(endTime)){
            throw new RuntimeException("课程正在上课，无法预约");
        }
        /*5.课程已经结束*/
        if (now.after(endTime)){
            throw new RuntimeException("课程已经结束");
        }
        /*6.开课前一个小时之内，才能预约*/
        if (now.before(courseTime)&&now.after(new Date(courseTime.getTime()-60*60*1000))){
            reserve.setReserveTime(new Date());
            reserve.setStatus(1);
            return reserveMapper.insert(reserve);
        }else {
            throw new RuntimeException("必须在开课的前一个小时内预约");
        }
    }

    @Override
    public List<Integer> getCidByMid(Integer mid) {
        return reserveMapper.selectCidByMid(mid);
    }

    @Override
    public List<ReserveVo> getCommentsByCid(Integer courseId) {
        return reserveMapper.selectCommentsByCid(courseId);
    }
}
